#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;

const int NUM = 10;

enum
{
    OK = 0,
    ERROR,
};

struct thread_data
{
    string _name;
    int _id;
    time_t _create_time;

    int _top;
    int _res;

    thread_data(const string& name, int id, int top) : _name(name), _id(id), _create_time(time(nullptr)), _top(top), _res(0)
    {}
    ~thread_data()
    {}
};

void* thread_routine(void* args)
{
    thread_data* td = static_cast<thread_data*>(args);

    for (int i = 0; i < td->_top; i++) 
        td->_res += i;

    cout << "thread name: " << td->_name << ", id: " << td->_id << ", ctime: " << td->_create_time << endl;
    cout << "res: " << td->_res << endl;

    delete td;
    pthread_exit(args);
    return nullptr;
}

int main()
{
    pthread_t tids[NUM];
    for (int i = 0; i < NUM; i++)
    {
        pthread_create(tids + i, nullptr, thread_routine, (void*)new thread_data("thread" + to_string(i+1), i+1, i));
    }

    // while (true)
    // {
    //     cout << "thread0 running " << pthread_self() << endl;
    //     sleep(1);
    // }

    for (int i = 0; i < NUM; i++)
    {
        void* ret = nullptr;
        if (pthread_join(tids[i], &ret) != 0) 
            cerr << "pthread_join error" << endl;
    }

    cout << "all thread is quit" << endl;

    return 0;
}
